package com.zengde.ai_sandbox.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

/**
 * 最简单的Echo WebSocket处理器，仅用于测试连接
 */
@Component
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@Profile("!test")
@Slf4j
public class EchoWebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        log.info("Echo WebSocket连接已建立: {}, 远程地址: {}", session.getId(), session.getRemoteAddress());
        try {
            session.sendMessage(new TextMessage("已连接到Echo服务器"));
        } catch (IOException e) {
            log.error("发送欢迎消息失败", e);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        String receivedMessage = message.getPayload();
        log.info("Echo服务器收到消息: {}", receivedMessage);
        
        try {
            // 直接回显收到的消息
            String echoResponse = "Echo: " + receivedMessage;
            session.sendMessage(new TextMessage(echoResponse));
            log.info("Echo服务器发送回复: {}", echoResponse);
        } catch (IOException e) {
            log.error("发送Echo回复失败", e);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        log.error("Echo WebSocket传输错误: {}", exception.getMessage(), exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        log.info("Echo WebSocket连接已关闭: {}, 状态: {}", session.getId(), status);
    }
} 